package my.db;

import java.util.List;

import javax.ejb.AccessTimeout;
import javax.ejb.LocalBean;
import javax.ejb.Lock;
import javax.ejb.LockType;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import my.Book;
import my.ILibrary;

@Singleton
@Startup
@LocalBean
@AccessTimeout(value = 5000)
// @ConcurrencyManagement(ConcurrencyManagementType.BEAN)
// @TransactionManagement(TransactionManagementType.BEAN)
public class LibraryDB implements ILibrary {

	@PersistenceContext(unitName = "library")
	private EntityManager em;

	// @Resource
	// private UserTransaction utx;

	@Lock(LockType.READ)
	@Override
	public List<Book> getBooks() {
		return em.createNamedQuery("findAllBooks", Book.class).getResultList();
	}

	@Lock(LockType.READ)
	@Override
	public Book getBook(String id) {
		return em.find(Book.class, id);
	}

	@Lock(LockType.WRITE)
	@Override
	public Book addBook(String id, String title) {
		Book book = new Book(id, title);
		// try {
		// utx.begin();

		em.persist(book);
		// em.flush();
		//
		// utx.commit();
		// } catch (Exception e) {
		// try {
		// utx.rollback();
		// } catch (Exception e2) {
		// e2.printStackTrace();
		// }
		// e.printStackTrace();
		// }
		return book;
	}

	@Lock(LockType.WRITE)
	@Override
	public Book updateBook(String id, String title) {
		// Query q = em.createNamedQuery("updateBook");
		// q.setParameter("isbn", id);
		// q.setParameter("title", title);
		// q.executeUpdate();
		//
		// return getBook(id);
		//
		Book book = getBook(id);
		if (book != null) {
			book.setTitle(title);
			em.merge(book);
		}
		return book;
	}

	@Lock(LockType.WRITE)
	@Override
	public Book removeBook(String id) {
		Book book = getBook(id);
		if (book != null) {
			// try {
			// utx.begin();

			em.remove(book);
			// em.flush();
			//
			// utx.commit();
			// } catch (Exception e) {
			// try {
			// utx.rollback();
			// } catch (Exception e2) {
			// e2.printStackTrace();
			// }
			// e.printStackTrace();
			// }
		}
		return book;
	}
}
